#!/bin/bash
script_path=$(cd "$(dirname "$0")" && pwd)
git_proxy=https://mirror.ghproxy.com/
ct_release=1.7.15
ct_url=https://github.com/containerd/containerd/releases/download/v${ct_release}/containerd-${ct_release}-linux-amd64.tar.gz
runc_release=1.1.12
runc_url=https://github.com/opencontainers/runc/releases/download/v${runc_release}/runc.amd64
cni_release=1.4.1
cni_url=https://github.com/containernetworking/plugins/releases/download/v${cni_release}/cni-plugins-linux-amd64-v${cni_release}.tgz
command -v jq >>/dev/null && country=$(curl -s https://ipinfo.io/$(curl ifconfig.me) | jq -r ".country") || country=$(curl -s https://ipinfo.io/$(curl ifconfig.me) | grep country | awk -F '"' '{print $4}')

ct_download() {
  if [ "$country" == "CN" ]; then
    curl -O ${git_proxy}${ct_url}
  else
    curl -O ${ct_url}
  fi
}

ct_install() {
  tar Cvxf /usr/local containerd-${ct_release}-linux-amd64.tar.gz
}

ct_configure() {
  if [ "$country" == "CN" ]; then
    curl -o /usr/lib/systemd/system/containerd.service ${git_proxy}https://raw.githubusercontent.com/containerd/containerd/main/containerd.service
  else
    curl -o /usr/lib/systemd/system/containerd.service https://raw.githubusercontent.com/containerd/containerd/main/containerd.service
  fi
}
runc_download() {
  if [ "$country" == "CN" ]; then
    curl -O ${git_proxy}${runc_url}
  else
    curl -O ${runc_url}
  fi
}
cni_download() {
  if [ "$country" == "CN" ]; then
    curl -O ${git_proxy}${cni_url}
  else
    curl -O ${cni_url}
  fi
}
cni_install() {
  [ -d /opt/cni/bin ] || mkdir -p /opt/cni/bin
  tar Cxzvf /opt/cni/bin cni-plugins-linux-amd64-v${cni_release}.tgz
}

main() {
  [ -f containerd-${ct_release}-linux-amd64.tar.gz ] || ct_download
  ct_install
  ct_configure
  systemctl daemon-reload
  systemctl enable --now containerd
  if [ $(systemctl is-active containerd) == "active" ]; then
    echo "containerd is running,deleting containerd archive"
    rm -rf ${script_path}/containerd-${ct_release}-linux-amd64.tar.gz
    echo "install containerd runc and cni-plugins"
    [ -f runc.amd64 ] || runc_download
    install -m 755 runc.amd64 /usr/local/sbin/runc
    [ -f cni-plugins-linux-amd64-v${cni_release}.tgz ] || cni_download
    cni_install
    rm -rf ${script_path}/runc.amd64
    rm -rf ${script_path}/cni-plugins-linux-amd64-v${cni_release}.tgz
  else
    echo "containerd failed,please check!!!"
  fi
  [ -d /etc/containerd ] || mkdir -p /etc/containerd
  if [ "$country" == "CN" ]; then
    curl -o /etc/containerd/config.toml https://gitee.com/chongxs/opscript/raw/master/config/containerd.toml
  else
    containerd config default > /etc/containerd/config.toml
  fi
}
main
